﻿/*
Date:2018-12-29 16:46:09
Remark:升级windows服务或WebService之工具
*/

using log4net;
using log4net.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace JQAutoUpdate
{
    class Program
    {
        static string[] _cmdArgs;
        /// <summary>
        /// 下载地址
        /// </summary>
        static string argsUpdateUrl = string.Empty;
        /// <summary>
        /// 更新类型
        /// </summary>
        static string argsUpdateType = string.Empty;
        /// <summary>
        /// 更新文件夹
        /// </summary>
        static string argsUpdateDir = string.Empty;
        /// <summary>
        /// 关联服务名(可选参数)
        /// </summary>
        static string argsProperName = string.Empty;
        /// <summary>
        /// 下载文件本地物理路径
        /// </summary>
        static string localFullPath = string.Empty;

        private static ILog logger = log4net.LogManager.GetLogger(typeof(Program));
        static void Main(string[] args)
        {
            //DoTest();
            //return;

            _cmdArgs = System.Environment.GetCommandLineArgs();
            logger.Info("进入升级，入参:");
            logger.Info(string.Join("-", _cmdArgs));
            if (_cmdArgs.Length > 3)
            {
                argsUpdateUrl = _cmdArgs[1];
                argsUpdateType = _cmdArgs[2];
                argsUpdateDir = _cmdArgs[3];
                #region Display Args
                Append($"Begin Update!");
                Append($"UpdateUrl: {argsUpdateUrl}");
                Append($"UpdateType: {argsUpdateType}");
                Append($"UpdateDir: {argsUpdateDir}");
                #endregion

                if (_cmdArgs.Length > 4)
                {
                    argsProperName = _cmdArgs[4];
                    Append($"ServiceName: {argsProperName}");
                }

                string localSavePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Temp");
                ToolKits.PrepareDirectory(localSavePath);
                string filename = string.Empty;
                switch(argsUpdateType)
                {
                    case "1":
                        filename = $"1-{DateTime.Now.ToString("yyyyMMddHHmmss")}";
                        break;
                    case "2":
                        filename = $"2-{DateTime.Now.ToString("yyyyMMddHHmmss")}";
                        break;
                    default:
                        filename = $"{DateTime.Now.ToString("yyyyMMddHHmmss")}";
                        break;
                }
                localFullPath = $"{localSavePath}\\{filename}.zip";
                Append("       Downloading...");
                try
                {
                    DownloadHelper.DownloadFile(argsUpdateUrl,
                                                localFullPath,
                                                (progress) =>
                                                {
                                                    Console.SetCursorPosition(0, Console.CursorTop - 1);
                                                    Console.WriteLine(progress.ToString("f1") + "%");
                                                });
                }
                catch (Exception ex)
                {
                    logger.Error("下载错误！", ex);
                    throw ex;
                }
                Append("Download Completed!");
                switch (argsUpdateType)
                {
                    case "0":
                        //desktopProgram
                        throw new NotImplementedException("desktopProgram Update Method Not Implemented");
                        break;
                    case "1":
                        //IIS
                        ExecuteIISUpdate();
                        break;
                    case "2":
                        //Service
                        ExecuteWindowsServiceUpdate();
                        break;
                    default:
                        break;
                }

            }
            else
            {
                throw new ArgumentException("参数个数不正确！");
            }
        }

        public static void ExecuteIISUpdate()
        {
            try
            {
                ToolKits.IISController(false);
                logger.Info("IIS Closed!");
                Append("IIS Closed!");
                Thread.Sleep(10 * 1000);
                logger.Info($"准备复制:从‘{localFullPath}’复制到{argsUpdateDir}");
                ToolKits.Unzip(localFullPath, argsUpdateDir);
                Append($"Unzip Completed!");
                ToolKits.IISController(true);
                logger.Info("IIS Launched!");
                Append($"Update Completed!");
            }
            catch (Exception ex)
            {
                logger.Error("IIS升级错误:",ex);
                throw ex;
            }
        }

        public static void ExecuteWindowsServiceUpdate()
        {
            //if (string.IsNullOrEmpty(argsProperName))
            //{
            //    throw new ArgumentException("缺少服务名参数！");
            //}
            try
            {
                ToolKits.ServiceController(false);
                Append($"Service {argsProperName} Closed!");
                logger.Info("Service Closed!");
                Thread.Sleep(10 * 1000);
                logger.Info($"准备复制:从‘{localFullPath}’复制到{argsUpdateDir}");
                ToolKits.Unzip(localFullPath, argsUpdateDir);
                Append($"Unzip Completed!");
                ToolKits.ServiceController(true);
                logger.Info("Service Launched!");
                Append($"Update Completed!");
            }
            catch (Exception ex)
            {
                logger.Error("升级服务错误:",ex);
                throw ex;
            }
        }

        public static void DoTest()
        {
            Append($"Begin Update!");
            //TEST IIS Control
            //ToolKits.IISController(false);

            //TEST Download
            //string url = "http://122.152.195.57:10002/PACS/7.0.0.2.zip";
            //string localSavePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Temp");
            //ToolKits.PrepareDirectory(localSavePath);
            //string filename = DateTime.Now.ToString("yyyyMMddHHmmss");
            //string localFullPath = $"{localSavePath}\\{filename}.zip";
            //DownloadHelper.HttpDownloadFile(url, localFullPath);

            //TEST UNZIP
            ToolKits.Unzip(@"d:\JQ\Source\JQAutoUpdate\JQAutoUpdate\bin\JQUpdate-1.0.1.0.zip",
                          @"D:\JQ\Source\JQAutoUpdate\JQAutoUpdate\bin\Debug\Temp");

            //TEST Report Progress
            //DownloadHelper.DownloadFile("http://47.92.31.227:10004/PACS/GUIZHOU/6.0.5.2.zip",
            //                             @"D:\JQ\Source\JQAutoUpdate\JQAutoUpdate\bin\Debug\Temp\20181229152529.zip",
            //                             (progress)=> 
            //                             {
            //                                 Console.SetCursorPosition(0, Console.CursorTop - 1);
            //                                 Console.WriteLine(progress.ToString("f1") + "%");
            //                             });

            //TEST WindowsService Start/Stop
            //ToolKits.ServiceController("1.JQStorageService",false);
        }

        /// <summary>
        /// 控制台输出
        /// </summary>
        /// <param name="str"></param>
        public static void Append(string str)
        {
            Console.WriteLine(str);
        }
    }


}
